package com.webamc.controller;

import com.webamc.common.enums.Fields;
import com.webamc.common.enums.Params;
import com.webamc.manager.IUserHandler;
import com.webamc.model.Result;
import com.webamc.model.User;
import com.webamc.util.CommonUtil;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * Date: Mar 14, 2009
 * Time: 12:09:55 AM
 */
public class UserAction extends AbstractAction {
    private Logger log = Logger.getLogger(UserAction.class);
    private IUserHandler userHandler;

    public void setUserHandler(IUserHandler userHandler) {
        this.userHandler = userHandler;
    }

    public ModelAndView update(HttpServletRequest req, HttpServletResponse res) {
        ModelAndView mv = new ModelAndView(getCreateView());

        // Authorization
        String action = req.getParameter(Params.ACTION);
        User u = getSessionUser(req);
        if (!isAuthorized(u, action)) {
            String msg = "Access Denied for role:" + u.getCategory()
                    + "& action:" + action + "to username=" + u.getUsername();
            log.info(msg);
            return setMV(mv, msg, getErrorView());
        }

        // Param validation
        Map m = getParams(req);
        Result r = getValidator().validate(m);
        if (r != null && !r.isPassed()) {
            log.info("Parameter validation error" + r.getMsgs());
            return setMV(mv, r.getMsgs(), getErrorView());
        }

        // Calling Business Layer to parse, validate & store
        try {
            User user = userHandler.update(m, u.getUserId());
            String msg = action + " action successful for User - " + user.getUsername();
            mv.addObject(Params.BEAN, user);
            setMV(mv, msg, getSingleView());
        } catch (Exception e) {
            log.error("Error occured while - " + e.getMessage(), e);
            setMV(mv, e.getMessage(), getErrorView());
        }

        log.info("Returning view =" + mv.getViewName());
        return mv;

    }


    public ModelAndView create(HttpServletRequest req, HttpServletResponse res) {
        ModelAndView mv = new ModelAndView(getCreateView());

        String action = req.getParameter(Params.ACTION);
        User u = getSessionUser(req);
        if (!isAuthorized(u, action)) {
            String msg = "Access Denied - role=" + u.getCategory()
                    + ", action=" + action + ", username=" + u.getUsername();
            log.info(msg);
            return setMV(mv, msg, getErrorView());
        }

        Map m = getParams(req);
        Result r = getValidator().validate(m);
        if (r != null && !r.isPassed()) {
            log.info("Parameter validation error" + r.getMsgs());
            return setMV(mv, r.getMsgs(), getErrorView());
        }

        try {
            User user = userHandler.create(m, u.getUserId());
            String msg = action + " action successful for User - " + user.getUsername();
            mv.addObject(Params.BEAN, user);
            setMV(mv, msg, getSingleView());
        } catch (Exception e) {
            log.error("Error occured while - " + e.getMessage(), e);
            setMV(mv, e.getMessage(), getErrorView());
        }

        log.info("Returning view =" + mv.getViewName());
        return mv;
    }

    public ModelAndView view(HttpServletRequest req, HttpServletResponse res) {
        ModelAndView mv = new ModelAndView(getCreateView());

        User u = getSessionUser(req);
        String action = req.getParameter(Params.ACTION);

        if (!isAuthorized(u, action)) {
            String msg = "Access Denied - role=" + u.getCategory()
                    + ", action=" + action + ", username=" + u.getUsername();
            log.info(msg);
            return setMV(mv, msg, getErrorView());
        }

        try {
            Map m = getParams(req);
            int userId = CommonUtil.getInt(m, Fields.USERID, 0);
            User user = userHandler.view(userId);
            mv.addObject(Params.BEAN, user);
            mv.setViewName(getSingleView());
        } catch (Exception e) {
            log.error("Error occured while - " + e.getMessage(), e);
            setMV(mv, e.getMessage(), getErrorView());
        }

        log.info("Returning view =" + mv.getViewName());
        return mv;

    }

    public ModelAndView beforeUpdate(HttpServletRequest req, HttpServletResponse res) {
        ModelAndView mv = view(req, res);

        User u = getSessionUser(req);
        String action = req.getParameter(Params.ACTION);
        if (!isAuthorized(u, action)) {
            String msg = "Access Denied - role=" + u.getCategory()
                    + ", action=" + action + ", username=" + u.getUsername();
            log.info(msg);
            return setMV(mv, msg, getErrorView());
        }

        mv.setViewName(getBeforeUpdateView());
        return mv;
    }

    public ModelAndView beforeCreate(HttpServletRequest req, HttpServletResponse res) {
        ModelAndView mv = new ModelAndView(getBeforeCreateView());
        User u = getSessionUser(req);
        String action = req.getParameter(Params.ACTION);

        if (!isAuthorized(u, action)) {
            String msg = "Access Denied - role=" + u.getCategory()
                    + ", action=" + action + ", username=" + u.getUsername();
            log.info(msg);
            return setMV(mv, msg, getErrorView());
        }
        return mv;
    }

    public ModelAndView beforeSearch(HttpServletRequest req, HttpServletResponse res) {
        ModelAndView mv = new ModelAndView(getBeforeSearchView());
        User u = getSessionUser(req);
        String action = req.getParameter(Params.ACTION);

        if (!isAuthorized(u, action)) {
            String msg = "Access Denied - role=" + u.getCategory()
                    + ", action=" + action + ", username=" + u.getUsername();
            log.info(msg);
            return setMV(mv, msg, getErrorView());
        }
        return mv;
    }

    public ModelAndView search(HttpServletRequest req, HttpServletResponse res) {
        ModelAndView mv = new ModelAndView(getListView());

        User u = getSessionUser(req);
        String action = req.getParameter(Params.ACTION);

        if (!isAuthorized(u, action)) {
            String msg = "Access Denied - role=" + u.getCategory()
                    + ", action=" + action + ", username=" + u.getUsername();
            log.info(msg);
            return setMV(mv, msg, getErrorView());
        }

        try {
            Map m = getParams(req);
            List users = userHandler.search(m);
            mv.addObject(Params.BEAN, users);
            log.info("List of users returned with size=" + users.size());
        } catch (Exception e) {
            log.error("Error occured while - " + e.getMessage(), e);
            setMV(mv, e.getMessage(), getErrorView());
        }

        log.info("Returning view =" + mv.getViewName());
        return mv;
    }

    public ModelAndView browse(HttpServletRequest req, HttpServletResponse res) {
        ModelAndView mv = new ModelAndView(getListView());
        User u = getSessionUser(req);
        String action = req.getParameter(Params.ACTION);

        if (!isAuthorized(u, action)) {
            String msg = "Access Denied - role=" + u.getCategory()
                    + ", action=" + action + ", username=" + u.getUsername();
            log.info(msg);
            return setMV(mv, msg, getErrorView());
        }

        try {
            List users = userHandler.browse();
            log.info("List of users returned with size=" + users.size());
            mv.addObject(Params.BEAN, users);
        } catch (Exception e) {
            log.error("Error occured while creating - " + e.getMessage(), e);
            setMV(mv, e.getMessage(), getErrorView());
        }

        log.info("Returning view =" + mv.getViewName());
        return mv;
    }

    protected ModelAndView handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException noSuchRequestHandlingMethodException, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        return super.handleNoSuchRequestHandlingMethod(noSuchRequestHandlingMethodException, httpServletRequest, httpServletResponse);    //To change body of overridden methods use File | Settings | File Templates.
    }
}
